package com.qf.deviceconsumer9001.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author q
 * @version V1.0
 * @date 2022/01/17
 **/
@RestController
@RequestMapping("/con/device")
public class DevConController {

    @Value("${server.port}")
    private String port;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * restTemplate 直接调用
     * @return
     */
    /*@GetMapping("/hello")
    public String hello(){
        //return "hello " + port;
        String result = restTemplate.getForObject("http://localhost:8001/device/hello", String.class);
        return "consumer -->" + result;
    }*/

    @GetMapping("/helloPro")
    public String hello(){
        return "devCon -> " + restTemplate.getForObject("http://DEVICE-PROVIDER/pro/device/hello", String.class);
    }

    @GetMapping("/testHystrix")
    //指定出现服务不可用时，调用服务降级方法
    @HystrixCommand(fallbackMethod = "fallbackError",
                    commandProperties = {
                        //指定超时时间
                        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
                    })
    public String testHystrix(Integer i){
        if (i == 1){
            i = 10/0;
        }
        if (i == 2){
            try {
                //服务超时：服务调用默认超时时间是1s
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "devCon -> " + restTemplate.getForObject("http://DEVICE-PROVIDER/pro/device/hello", String.class);
    }

    //服务降级的方法
    public String fallbackError(Integer i){
        //返回托底数据
        return "ribbon hystrix !!";
    }

}
